package org.bing.engine.controller.service;

import java.util.ArrayList;
import java.util.List;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.bing.engine.common.message.Filter;
import org.bing.engine.common.message.Message;
import org.bing.engine.common.message.Router;
import org.bing.engine.core.domain.Node;
import org.bing.engine.utility.helper.GuidGenerator;

public class MessageSender {
    private static final Log logger = LogFactory.getLog(MessageSender.class);
    private RemoteFactory factory;
    private List<Filter> filters;

    public void setRemoteFactory(RemoteFactory fac) {
        this.factory = fac;
    }

    public void setFilters(List<Filter> filters) {
        this.filters = filters;
    }

    public void init() {
        if (filters == null) {
            filters = new ArrayList<Filter>();
        }
    }

    public void send(Node node, Message msg) {
        if (msg.getId() == null) {
            msg.setId(GuidGenerator.generate());
        }
        for (Filter filter : filters) {
            filter.doFilter(msg);
        }
        Router router = factory.getRemoteService(node, Router.class);
        Object res = router.route(msg);
        logger.info("Result:" + res);
    }
}
